package com.example.blog.controller;

import com.example.blog.enums.ResultEnums;
import com.example.blog.model.Result;
import com.example.blog.model.UserInfo;
import com.example.blog.service.UserService;
import com.example.blog.util.JWTutil;
import com.example.blog.util.SecurityUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName,String password){
        Assert.hasLength(userName,"用户名不能为空");
        Assert.hasLength(password,"密码不能为空");

        UserInfo userInfo = userService.getInfo(userName);
        if(userInfo==null||userInfo.getId()<=0){
            log.error("没有对象");
            return Result.fail(ResultEnums.WRONG_PARAM.getCode(),"用户不存在");
        }
        if (!SecurityUtils.verify(password,userInfo.getPassword())){
            log.error("密码不对");
            return Result.fail(ResultEnums.WRONG_PARAM.getCode(),"密码不正确");
        }
//        if (!password.equals(userInfo.getPassword())){
//            log.error("密码不对");
//            return Result.fail(ResultEnums.WRONG_PARAM.getCode(),"密码不正确");
//        }
        Map<String,Object> cliams = new HashMap<>();
        cliams.put("id",userInfo.getId());
        cliams.put("name",userInfo.getUserName());

        String jwt = JWTutil.genJWT(cliams);
        return Result.success(jwt);
    }

    //判断用户是否登录
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        String token = request.getHeader("user_token");
        Integer userId = JWTutil.getUserIdByToken(token);
        Assert.notNull(userId,"用户未登录");
        UserInfo userInfo = userService.getInfoById(userId);
        return userInfo;
    }

    //根据博客ID获取博客作者信息
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfoByBlogId(Integer blogId){
        Assert.notNull(blogId,"博客ID不能为null");
        return userService.getInfoByBlogId(blogId);
    }
}
